﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using Web.PuntoDeVenta.Code;
using CrmContacto.Contracts;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Text;
using CrmContacto.Contracts.Enums;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework.Misc;
using Web.Framework.Search;
using CrmContacto.Contracts.Contracts;
using Web.PuntoDeVenta.Code.FrontEnd;
using Web.Framework.Svc;

namespace Web.PuntoDeVenta.App
{
    public partial class Customer : BasePage
    {
        public CustomerSearchParam SearchParam
        {
            get
            {
                return (CustomerSearchParam)ViewState["SearchParam"];
            }
            set
            {
                ViewState["SearchParam"] = value;
            }
        }

        public PtoVentaRegistroCliente customerCurrent
        {
            get
            {
                return (PtoVentaRegistroCliente)ViewState["customerCurrent"];
            }
            set
            {
                ViewState["customerCurrent"] = value;
            }
        }

        public List<PtoVentaRegistroCliente> RegistroClienteList
        {
            get
            {
                return (List<PtoVentaRegistroCliente>)ViewState["RegistroClienteList"];
            }
            set
            {
                ViewState["RegistroClienteList"] = value;
            }
        }

        private enum ModoPantalla
        {
            SinEspecificar = 0,
            Venta = 1,
            EdicionContacto = 2,
        }

        private const string CookieNameModo = "CookieNameModo";
        private const string CookieNameRememberModo = "CookieNameRememberModo";

        private ModoPantalla Modo
        {
            get
            {
                ModoPantalla modoReturn = ModoPantalla.SinEspecificar;
                if (Session[CookieNameModo] != null)
                {
                    modoReturn = (ModoPantalla)Session[CookieNameModo];
                }
                else
                {
                    if (RememberMode)
                    {
                        string cookieValue = HttpHelper.GetCookieValue(CookieNameModo, this.Request);
                        if (!String.IsNullOrEmpty(cookieValue))
                        {
                            modoReturn = (ModoPantalla)Convert.ToInt32(cookieValue);
                        }
                    }
                }

                return modoReturn;
            }
            set
            {
                Session[CookieNameModo] = value;
            }
        }

        private bool RememberMode
        {
            get
            {
                string cookieValue = HttpHelper.GetCookieValue(CookieNameRememberModo, this.Request);
                if (String.IsNullOrEmpty(cookieValue))
                {
                    return false;
                }
                else
                {
                    return Convert.ToBoolean(cookieValue);
                }
            }
            set
            {
                if (value)
                {
                    HttpHelper.SetCookieValue(CookieNameModo, this.Response, Convert.ToString((int)Modo));
                    HttpHelper.SetCookieValue(CookieNameRememberModo, this.Response, true.ToString());
                }
                else
                {
                    HttpHelper.SetCookieValue(CookieNameRememberModo, this.Response, false.ToString());
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ExceptionManager.Instance.WebMessager = (SiteMaster)this.Master;
            lnkAgregarClienteNuevoDesdeEdit.Visible = false;

            this.lnkActivarContacto.Attributes.Add("aspnetid", this.lnkActivarContacto.UniqueID);
            this.btnBuscar.Attributes.Add("aspnetid", this.btnBuscar.UniqueID);

            CargarTotalesDeVenta();

            if (!this.IsPostBack)
            {
                LoadCombos();

                // Oculto todos los paneles menos el de buscar
                if (Modo == ModoPantalla.SinEspecificar)
                {
                    this.pnlHome.Visible = true;
                    this.pnlSearch.Visible = false;
                    this.pnlSearchResults.Visible = false;
                    this.pnlCustomerEdit.Visible = false;
                }
                else
                {
                    this.pnlHome.Visible = false;
                    this.pnlSearch.Visible = true;
                    this.pnlSearchResults.Visible = false;
                    this.pnlCustomerEdit.Visible = false;
                }
            }

            this.validationSearchFactura.Attributes.Add("class", "searchFacturamarginRight visibleNone");
            this.validationSearchEmail.Attributes.Add("class", "visibleNone");
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            if (customerCurrent != null)
            {
                if (customerCurrent.Estado == (int)EstadoCliente.Inactivo)
                {
                    pnlCustomerEdit.Enabled = false;
                    lnkActivarContacto.Visible = true;
                }
                else
                {
                    pnlCustomerEdit.Enabled = true;
                    lnkActivarContacto.Visible = false;
                }
            }
            else
            {
                pnlCustomerEdit.Enabled = false;
                lnkActivarContacto.Visible = false;
            }
        }

        private void CargarTotalesDeVenta()
        {
            object sMarca = Session["Marca"];

            if (sMarca != null)
            {
                Marca marca = (Marca)sMarca;
                List<string> ptoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);
                int ptoVentaId = Convert.ToInt32(ptoVta[0]);
                var ventasTotales = TotalDeVentasManager.Instance.GetTotales(marca, ptoVentaId);

                if (ventasTotales.ConValores)
                {
                    if (ventasTotales.CantidadSucursal > ventasTotales.CantidadVentasTotal)
                    {
                        lblCantidadTotales.Text = LocalizationProvider.Instance["PDV.TasaConversion.CalculoMayorACien"];
                    }
                    else
                    {
                        lblCantidadTotales.Text = string.Format(LocalizationProvider.Instance["Pdv.Mensaje.CantidadVentasTotales"], ventasTotales.Ratio, ventasTotales.CantidadSucursal, ventasTotales.CantidadVentasTotal, DateTime.Now.AddDays(-1));                        
                    }

                    pnlTotales.Visible = true;
                }
                else
                {
                    pnlTotales.Visible = false;
                }
            }
        }

        private void LoadCombos()
        {
            
            
            UIHelper.LoadCboRange(1, 31, this.cboCumpleDia, LocalizationProvider.Instance["CboSinDia"]);
            UIHelper.LoadCboMonth(this.cboCumpleMes, LocalizationProvider.Instance["CboSinMes"]);
            UIHelper.LoadCboRange(1930, 2030, this.cboCumpleAnio, LocalizationProvider.Instance["CboSinAnio"]);

            int paisId = Convert.ToInt32(ConfigurationManager.AppSettings["paisPorDefecto"]);
            List<MaestroBase> tipoDocumento = WebServiceHelper.GetTipoDocumento(paisId);
            UIHelper.LoadCbo(tipoDocumento, cboTipoDocumento, LocalizationProvider.Instance["CboSinTipoDoc"]);

            string paisPorDefecto = ConfigurationManager.AppSettings["paisPorDefecto"];
            List<Pais> pais = WebServiceHelper.GetPaises();
            UIHelper.LoadCbo(pais, cboPais, LocalizationProvider.Instance["CboSinPais"]);

            UIHelper.LoadEstados<SexoEnum>(this.cboSexo, LocalizationProvider.Instance["DropDown.SinEspecificar"]);

            UIHelper.LoadEstados<ContactoCantidadHijos>(this.cboCantidadHijos, LocalizationProvider.Instance["DropDown.SinEspecificar"]);

            UIHelper.LoadEstados<ContactoEdadHijoMenor>(this.cboEdadHijoMenor, LocalizationProvider.Instance["DropDown.SinEspecificar"]);

            if (pais.Where(p => p.Id.ToString() == paisPorDefecto).Count() > 0)
            {
                this.cboPais.SelectedValue = paisPorDefecto;
            }

            LoadComboProvincias();
        }

        private void SeleccionarTipoDocumentoDefault()
        {
            string tipoDocDefault = ConfigurationManager.AppSettings["tipoDocPorDefecto"];

            foreach (ListItem item in this.cboTipoDocumento.Items)
            {
                if (item.Value == tipoDocDefault)
                {
                    this.cboTipoDocumento.SelectedValue = item.Value;
                    break;
                }
            }
        }

        private void LoadComboProvincias()
        {
            List<MaestroBase> provincias = WebServiceHelper.GetProvincias(Convert.ToInt32(this.cboPais.SelectedValue));
            UIHelper.LoadCbo(provincias, cboProvincia, LocalizationProvider.Instance["CboSinProvincia"]);
        }

        private void SeleccionarCliente(CustomerSearchResult registroClienteResult)
        {
            ModoGrilla();

            RegistroClienteList = registroClienteResult.Resultados; // Guardo en el viewstate

            //this.GridClientes.DataSource = RegistroClienteList;
            //this.GridClientes.DataBind();

            //if (registroClienteResult.ResultadosTruncados)
            //{
            //    ((SiteMaster)this.Master).ShowMessage(LocalizationProvider.Instance["MensajeResultadosTruncados"], WebMessageType.Notification);
            //}
        }

        private void ModoGrilla()
        {
            this.pnlHome.Visible = false;
            this.pnlSearch.Visible = true;
            this.pnlSearchResults.Visible = true;
            this.pnlCustomerEdit.Visible = false;
        }

        private void CargarClienteExistente(PtoVentaRegistroCliente ptoVentaRegistroCliente)
        {

            this.pnlHome.Visible = false;
            this.pnlSearch.Visible = false;
            this.pnlSearchResults.Visible = false;
            this.pnlCustomerEdit.Visible = true;       
            btnBitacora.Visible = true;
            btnVentas.Visible = true;

            hidClienteId.Value = ptoVentaRegistroCliente.Id.ToString();

            customerCurrent = ptoVentaRegistroCliente;

            // Bind
            if (customerCurrent.TipoDocumentoId.HasValue)
            {
                this.cboTipoDocumento.SelectedValue = customerCurrent.TipoDocumentoId.Value.ToString();
            }
            else
            {
                if (customerCurrent.Id == 0)
                {
                    //SeleccionarTipoDocumentoDefault();
                }
            }

            if (customerCurrent.Dni.HasValue)
            {
                this.txtDNI.Text = customerCurrent.Dni.ToString();
            }

            this.txtFechaVenta_1.Value = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtEmail.Text = customerCurrent.Email;
            this.txtEmailVerify.Text = this.txtEmail.Text;
            this.txtNombre.Text = customerCurrent.Nombre;
            this.txtApellido.Text = customerCurrent.Apellido;
            this.hidEmail.Value = string.Empty;
            this.txtDomicilio.Text = customerCurrent.Domicilio;
            this.txtCodigoPostal.Text = customerCurrent.CodigoPostal;
            this.txtTelefono.Text = customerCurrent.Telefono;
            this.txtCredencial.Text = customerCurrent.NroCredencial;
            if (customerCurrent.Id == 0)
            {
                this.chkDeseaRecibirEmails.Checked = true; // Por defecto está seleccionado
            }
            else
            {
                this.chkDeseaRecibirEmails.Checked = customerCurrent.DeseaRecibirEmails;
            }

            if (customerCurrent.CantidadHijos.HasValue)
            {
                this.cboCantidadHijos.SelectedValue = customerCurrent.CantidadHijos.Value.ToString();
            }

            if (customerCurrent.EdadHijoMenor.HasValue)
            {
                this.cboEdadHijoMenor.SelectedValue = customerCurrent.EdadHijoMenor.Value.ToString();
            }

            if (customerCurrent.Sexo.HasValue)
            {
                this.cboSexo.SelectedValue = customerCurrent.Sexo.Value.ToString();
            }

            if (customerCurrent.FechaUltimaCompra.HasValue)
            {
                this.txtFechaUltimaCompra.Text = customerCurrent.FechaUltimaCompra.Value.ToString("dd/MM/yyyy");
            }

            UIHelper.LoadLst(customerCurrent.Categorias, this.lstCategoria, string.Empty); //, allDisabled: true);
            //Selecciono todos los items, ya que solo muestro las del cliente
            foreach (ListItem item in lstCategoria.Items)
            {
                item.Selected = true;
            }

            if (customerCurrent.EstadoEmail.HasValue)
            {
                if (customerCurrent.EstadoEmail.Value == (int)EstadoEmail.ReboteHard)
                {
                    spanEmailInvalido.Attributes["class"] = "errorAsterisk"; //por default ya está oculto
                    this.hidEmail.Value = customerCurrent.Email;
                }
            }

            if (customerCurrent.NacionalidadId.HasValue)
            {
                this.cboPais.SelectedValue = customerCurrent.NacionalidadId.Value.ToString();
                LoadComboProvincias();

                if (customerCurrent.ProvinciaId.HasValue)
                {
                    this.cboProvincia.SelectedValue = customerCurrent.ProvinciaId.Value.ToString();
                }
            }

            if (customerCurrent.CumpleDia.HasValue)
            {
                this.cboCumpleDia.SelectedValue = customerCurrent.CumpleDia.Value.ToString();
            }
            else
            {
                this.cboCumpleDia.SelectedValue = UIHelper.cboNullValue;
            }

            if (customerCurrent.CumpleMes.HasValue)
            {
                this.cboCumpleMes.SelectedValue = customerCurrent.CumpleMes.Value.ToString();
            }
            else
            {
                this.cboCumpleMes.SelectedValue = UIHelper.cboNullValue;
            }

            if (customerCurrent.CumpleAnio.HasValue)
            {
                this.cboCumpleAnio.SelectedValue = customerCurrent.CumpleAnio.Value.ToString();
            }
            else
            {
                this.cboCumpleAnio.SelectedValue = UIHelper.cboNullValue;
            }

            RegistrarJsParaValidarConfiguracionEmpresa();
            LoadCboCampana();
        }

        private void LoadCboCampana()
        {
            cboCampania_1.Items.Clear();

            List<string> ptoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);
            int ptoVtaId = Convert.ToInt32(ptoVta[0]);

            CampaniasActivasSearch search = new CampaniasActivasSearch();
            search.EmpresaId = BaseMasterPage.CompanyId;
            search.PtoVtaId = ptoVtaId;
            if(customerCurrent != null && customerCurrent.Id != 0)
            {
                search.ContactoId = customerCurrent.Id;
            }

            List<MaestroBase> campanias = WebServiceHelper.GetCampaniasActivas(search);
            UIHelper.LoadCbo(campanias, cboCampania_1, LocalizationProvider.Instance["CboSinPromocion"]);
        }

        private void RegistrarJsParaValidarConfiguracionEmpresa()
        {
            // Para esta pantalla cargo la validacion de empresa
            var configEmpresaList = BasePage.GetCompanyConfigurationKeyValue(this, BaseWebPage.CompanyId);

            var configEmpresaEdad = configEmpresaList.Where(c => c.Key == CommonConstants.ValidacionMaximoEdad).SingleOrDefault();
            if (configEmpresaEdad != null)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "companyConfig", "<script> var _maximoEdad = " + configEmpresaEdad.Value + ";</script>");
            }
        }

        private bool EsClienteActualizado()
        {
            bool esActualizado = false;
            PtoVentaRegistroCliente newCustomer = new PtoVentaRegistroCliente();
            SetData(newCustomer);

            if (customerCurrent.Id != 0)
            {
                // analizo si hubo un cambio
                if (customerCurrent.TipoDocumentoId != newCustomer.TipoDocumentoId ||
                customerCurrent.Dni != newCustomer.Dni ||
                customerCurrent.Email != newCustomer.Email ||
                !CompareString.AreEqual(customerCurrent.Nombre, newCustomer.Nombre) ||
                !CompareString.AreEqual(customerCurrent.Apellido, newCustomer.Apellido) ||
                customerCurrent.NacionalidadId != newCustomer.NacionalidadId ||
                customerCurrent.ProvinciaId != newCustomer.ProvinciaId ||
                !CompareString.AreEqual(customerCurrent.Domicilio, newCustomer.Domicilio) ||
                !CompareString.AreEqual(customerCurrent.CodigoPostal, newCustomer.CodigoPostal) ||
                customerCurrent.CumpleDia != newCustomer.CumpleDia ||
                customerCurrent.CumpleMes != newCustomer.CumpleMes ||
                customerCurrent.CumpleAnio != newCustomer.CumpleAnio ||
                customerCurrent.Sexo != newCustomer.Sexo ||
                !CompareString.AreEqual(customerCurrent.Telefono, newCustomer.Telefono) ||
                !CompareString.AreEqual(customerCurrent.NroCredencial, newCustomer.NroCredencial) ||
                customerCurrent.DeseaRecibirEmails != newCustomer.DeseaRecibirEmails ||
                customerCurrent.CantidadHijos != newCustomer.CantidadHijos ||
                customerCurrent.EdadHijoMenor != newCustomer.EdadHijoMenor)
                {
                    esActualizado = true;
                }
            }

            return esActualizado;
        }

        private void SaveCustomer()
        {
            if (customerCurrent != null)
            {
                bool esActualizado = EsClienteActualizado();

                SetData(customerCurrent);
                PtoVentaRegistroCliente savedCustomer = WebServiceHelper.SaveCustomer(customerCurrent);

                StringBuilder mensajeExito = new StringBuilder();
                if (customerCurrent.Id == 0)
                {
                    mensajeExito.Append(LocalizationProvider.Instance["ContactoSavePtoVta"]);
                }
                else if (esActualizado)
                {
                    mensajeExito.Append(LocalizationProvider.Instance["ContactoUpdatePtoVta"]);
                }

                if (mensajeExito.Length > 0)
                {
                    mensajeExito.Append("<br />");
                }

                if (!String.IsNullOrEmpty(savedCustomer.ServiceMessage))
                {
                    mensajeExito.Append(savedCustomer.ServiceMessage);
                    customerCurrent.ServiceMessage = string.Empty;
                    customerCurrent.ServiceMessageOK = string.Empty;
                }
                else if (customerCurrent.Facturas.Count > 0)
                {
                    mensajeExito.Append(LocalizationProvider.Instance["ContactoSavePtoVtaFactura"]);
                }

                if (!String.IsNullOrEmpty(savedCustomer.ServiceMessageOK))
                {
                    if (mensajeExito.Length > 0)
                    {
                        mensajeExito.Append("<br />");
                    }

                    mensajeExito.Append(savedCustomer.ServiceMessageOK);
                    customerCurrent.ServiceMessageOK = string.Empty;
                }

                customerCurrent = savedCustomer;

                ((SiteMaster)this.Master).ShowMessage(mensajeExito.ToString(), WebMessageType.Notification);

                if (RememberMode)
                {
                    if (Modo == ModoPantalla.EdicionContacto)
                    {
                        EntrarEnModoActualizacion();
                    }
                    else if (Modo == ModoPantalla.Venta)
                    {
                        EntrarEnModoVenta();
                    }
                    else
                    {
                        EntrarEnModoSinEspecificar();
                    }
                }
                else
                {
                    EntrarEnModoSinEspecificar();
                }
            }
        }

        private void ResetFields()
        {
            try
            {
                this.cboTipoDocumento.SelectedValue = UIHelper.cboNullValue;  // ConfigurationManager.AppSettings["tipoDocPorDefecto"];               
            }
            catch
            {
            }

            try
            {
                this.cboPais.SelectedValue = ConfigurationManager.AppSettings["paisPorDefecto"];
                LoadComboProvincias();
            }
            catch
            {
            }

            this.cboProvincia.SelectedValue = UIHelper.cboNullValue;
            this.cboCumpleDia.SelectedValue = UIHelper.cboNullValue;
            this.cboCumpleMes.SelectedValue = UIHelper.cboNullValue;
            this.cboCumpleAnio.SelectedValue = UIHelper.cboNullValue;
            this.cboCantidadHijos.SelectedValue = UIHelper.cboNullValue;
            this.cboEdadHijoMenor.SelectedValue = UIHelper.cboNullValue;

            this.txtDNI.Text = string.Empty;
            this.txtEmail.Text = string.Empty;
            this.txtNombre.Text = string.Empty;
            this.txtApellido.Text = string.Empty;
            this.txtFactura_1.Value = string.Empty;
            this.txtCodigoMarketing_1.Value = string.Empty;
            this.txtFechaUltimaCompra.Text = string.Empty;
        }

        private void SetData(PtoVentaRegistroCliente customer)
        {
            customer.UserName = HttpContext.Current.User.Identity.Name;
            customer.TipoDocumentoId = UIHelper.GetIntFromInputCbo(cboTipoDocumento);
            customer.EmpresaId = BaseMasterPage.CompanyId;
            if (!String.IsNullOrEmpty(this.txtDNI.Text))
            {
                customer.Dni = decimal.Parse(this.txtDNI.Text);
            }
            else
            {
                customer.Dni = null;
            }

            customer.Email = this.txtEmail.Text;
            customer.Nombre = this.txtNombre.Text;
            customer.Apellido = this.txtApellido.Text;
            customer.Domicilio = this.txtDomicilio.Text;
            customer.CodigoPostal = this.txtCodigoPostal.Text;
            customer.Telefono = this.txtTelefono.Text;
            customer.NroCredencial = this.txtCredencial.Text;
            customer.DeseaRecibirEmails = this.chkDeseaRecibirEmails.Checked;
            customer.Sexo = UIHelper.GetIntFromInputCbo(this.cboSexo);

            if (customer.PuntoDeVentaId == 0)
            {
                List<string> ptoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);
                customer.PuntoDeVentaId = Convert.ToInt32(ptoVta[0]);
            }

            customer.NacionalidadId = UIHelper.GetIntFromInputCbo(this.cboPais);
            customer.ProvinciaId = UIHelper.GetIntFromInputCbo(this.cboProvincia);
            customer.CumpleDia = (short?)UIHelper.GetIntFromInputCbo(cboCumpleDia);
            customer.CumpleMes = (short?)UIHelper.GetIntFromInputCbo(cboCumpleMes);
            customer.CumpleAnio = (short?)UIHelper.GetIntFromInputCbo(cboCumpleAnio);
            customer.CantidadHijos = UIHelper.GetIntFromInputCbo(cboCantidadHijos);
            customer.EdadHijoMenor = UIHelper.GetIntFromInputCbo(cboEdadHijoMenor);

            customer.SubPuntoDeVentaId = PuntoDeVentaCurrentSession.SubPuntoDeVentaIdActual;

            SetDataForSells(customer);
        }

        /// <summary>
        /// Carga los datos de una venta
        /// </summary>
        /// <param name="customer"></param>
        private void SetDataForSells(PtoVentaRegistroCliente customer)
        {
            //txtFactura_1
            //cboCampania_1
            //txtFechaVenta_1
            List<FacturaCampanaPtoVta> ventas = new List<FacturaCampanaPtoVta>();
            const string facturaPrefix = "txtFactura_";
            const string campanaPrefix = "cboCampania_";
            const string fechaVtaPrefix = "txtFechaVenta_";
            const string cuponPrefix = "txtCodigoMarketing_";
            int i = 1;

            string facturaName = facturaPrefix + i.ToString();
            string campaniaName = campanaPrefix + i.ToString();
            string fechaVtaName = fechaVtaPrefix + i.ToString();
            string cuponName = cuponPrefix + i.ToString();
            bool salir = String.IsNullOrEmpty(this.txtFactura_1.Value);            

            while (!salir)
            {
                FacturaCampanaPtoVta venta = new FacturaCampanaPtoVta();

                if (i == 1)
                {
                    venta.Factura = this.txtFactura_1.Value;
                    Control ctrlCampania = pnlFacturas.FindControl(campaniaName);
                    if (ctrlCampania != null)
                    {
                        DropDownList cboCampania = (DropDownList)ctrlCampania;
                        venta.AccionDeMarketingId = UIHelper.GetIntFromInputCbo(cboCampania);
                    }

                    venta.FechaDeVenta = UIHelper.GetDateTimeFromInputText(this.txtFechaVenta_1.Value);
                    venta.Cupon = this.txtCodigoMarketing_1.Value;
                }
                else
                {
                    venta.Factura = this.Request.Form[facturaName];

                    int campaniaValue = Convert.ToInt32(this.Request.Form[campaniaName]);
                    if (this.Request.Form[campaniaName] != UIHelper.cboNullValue)
                    {
                        venta.AccionDeMarketingId = campaniaValue;
                    }

                    venta.FechaDeVenta = UIHelper.GetDateTimeFromInputText(this.Request.Form[fechaVtaName]);
                    venta.Cupon = this.Request.Form[cuponName];
                }

                venta.PuntoDeVentaId = Convert.ToInt32(HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request)[0]);                
                ventas.Add(venta);

                i++;
                facturaName = facturaPrefix + i.ToString();
                campaniaName = campanaPrefix + i.ToString();
                fechaVtaName = fechaVtaPrefix + i.ToString();
                cuponName = cuponPrefix + i.ToString();

                salir = this.Request.Form[facturaName] == null;
            }

            customer.Facturas = ventas;
        }

        private void EntrarEnModoVenta()
        {
            Modo = ModoPantalla.Venta;
            parrafoSearch.Visible = true;
            this.txtDniEmail.Text = string.Empty;
            this.txtSearchFactura.Text = string.Empty;

            this.pnlHome.Visible = false;
            this.pnlSearch.Visible = true;
            this.pnlSearchResults.Visible = false;
            this.pnlCustomerEdit.Visible = false;
        }

        private void EntrarEnModoActualizacion()
        {
            Modo = ModoPantalla.EdicionContacto;
            parrafoSearch.Visible = false;
            this.txtDniEmail.Text = string.Empty;

            this.pnlHome.Visible = false;
            this.pnlSearch.Visible = true;
            this.pnlSearchResults.Visible = false;
            this.pnlCustomerEdit.Visible = false;
        }

        private void EntrarEnModoSinEspecificar()
        {
            Modo = ModoPantalla.SinEspecificar;
            if (RememberMode)
            {
                this.chkRecordarMiDecision.Checked = RememberMode;
            }

            customerCurrent = null;

            this.pnlHome.Visible = true;
            this.pnlSearch.Visible = false;
            this.pnlSearchResults.Visible = false;
            this.pnlCustomerEdit.Visible = false;
        }

        protected void GridClientes_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int clienteId = Convert.ToInt32(this.GridClientes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);

                    var customer = RegistroClienteList.Where(c => c.Id == clienteId).SingleOrDefault();

                    if (customer != null)
                    {
                        RegistroClienteList.Clear();
                        lblClienteEdit.Text = LocalizationProvider.Instance["TitleEdicionDeCliente"];
                        this.lnkAgregarClienteNuevoDesdeEdit.Visible = false;
                        this.CargarClienteExistente(customer);
                    }
                    else
                    {
                        BindToGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridClientes_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridClientes.PageIndex = e.NewPageIndex;

                BindToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridClientes_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //try
            //{
            //    if (e.Row.RowType == DataControlRowType.DataRow)
            //    {
            //        e.Row.Cells[0].Attributes.Add("title", "Editar");
            //        e.Row.Cells[1].Attributes.Add("title", "Eliminar");
            //        ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
            //        btnEliminarCtrl.OnClientClick = string.Format("return confirm('Está seguro que desea eliminar el siguiente registro? {0}')", ((Temporada)e.Row.DataItem).Nombre);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    ExceptionManager.Instance.HandleException(ex);
            //}
        }

        protected void GridClientes_DataBound(object sender, EventArgs e)
        {
            try
            {
                if (CustomerSearchProvider != null)
                {
                    CustomerSearchResult searchResult = CustomerSearchProvider.SearchResult;

                    if (searchResult != null && searchResult.TotalDeResultados > 0)
                    {
                        // visibilidad
                        string resultStr = string.Format(LocalizationProvider.Instance["Bo.SearchContacto.ResultString"], searchResult.TotalDeResultados);
                        lblSearchResult.Text = resultStr;
                    }
                    else
                    {
                        lblSearchResult.Text = LocalizationProvider.Instance["Bo.SearchContacto.NoResultsString"];
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCustomer_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            try
            {
                if (e.Exception != null)
                {
                    ExceptionManager.Instance.HandleException(e.Exception);
                    e.ExceptionHandled = true;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        public CustomerSearchObjectDataSourceProvider CustomerSearchProvider { get; set; }

        protected void CustomerObjectDs_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            GridViewSearchObjectDataSource searchProvider = new GridViewSearchObjectDataSource();
            this.CustomerSearchProvider = new CustomerSearchObjectDataSourceProvider();
            this.CustomerSearchProvider.SearchParam = this.SearchParam;
            //this.CustomerSearchProvider.WebServiceHelper = this.WebServiceHelper;

            searchProvider.Provider = this.CustomerSearchProvider;
            e.ObjectInstance = searchProvider;
        }

        private void BindToGrid()
        {
            //int pageSize = Convert.ToInt32(cboRegistros.SelectedValue);
            //if (pageSize == 0)
            //{
            //    this.GridCustomer.AllowPaging = false;
            //}
            //else
            //{

            ModoGrilla();

            this.GridClientes.AllowPaging = true;
            //}

            this.GridClientes.DataSourceID = "CustomerObjectDs";
            this.GridClientes.DataBind();

            RegistroClienteList = CustomerSearchProvider.SearchResult.Resultados;
        }

        protected void lnkActivarContacto_Click(object sender, EventArgs e)
        {
            try
            {
                if (customerCurrent != null && customerCurrent.Estado == (int)EstadoCliente.Inactivo)
                {                    
                    ServiceOptions options = new ServiceOptions();
                    options.UserName = HttpContext.Current.User.Identity.Name;
                    options.CompanyId = BaseMasterPage.CompanyId;
                    WebServiceHelper.ActivarEntidad(options, typeof(Cliente).Name, (int)EstadoCliente.Activo, customerCurrent.Id);
                    customerCurrent.Estado = (int)EstadoCliente.Activo;
                    lnkActivarContacto.Visible = false;
                    lblClienteEdit.Text = LocalizationProvider.Instance["TitleEdicionDeCliente"];
                    lblClienteEditLine2.Text = LocalizationProvider.Instance["MensajeCargueDatosCliente"];
                    this.lnkAgregarClienteNuevoDesdeEdit.Visible = false;
                    this.CargarClienteExistente(customerCurrent);
                    // Recargar
                }

                //if (currentCliente.Id != 0 && currentCliente.Estado.HasValue)
                //{
                //    EstadoCliente estado = (EstadoCliente)currentCliente.Estado;
                //    currentCliente.Estado = (int)(estado == EstadoCliente.Activo ? EstadoCliente.Inactivo : EstadoCliente.Activo);
                //    WebServiceHelper.ActivarEntidad(currentCliente.GetType().Name, currentCliente.Estado, currentCliente.Id);
                //    var tmpCurrentCliente = WebServiceHelper.GetCustomerById(WebServiceHelper.ServiceOptionsDefault, currentCliente.Id, new ClienteByIdOptions() { LoadBasicInfo = false, LoadSales = false, LoadBitacora = true, LoadListasDeDistribucion = false });
                //    currentCliente.Bitacora.Clear();
                //    currentCliente.Bitacora.AddRange(tmpCurrentCliente.Bitacora);
                //    Bind();
                //}

            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            string dniOrEmail = this.txtDniEmail.Text;
            try
            {
                ResetFields();

                SearchParam = new CustomerSearchParam();
                SearchParam.PageSize = this.GridClientes.PageSize;
                SearchParam.Nombre = dniOrEmail;
                SearchParam.EmpresaId = BaseMasterPage.CompanyId;

                BindToGrid();

                var searchResult = this.CustomerSearchProvider.SearchResult;

                if (searchResult.Resultados.Count == 0)
                {
                    CargarClienteNuevo(dniOrEmail);
                }
                else if (searchResult.Resultados.Count == 1)
                {
                    // Cliente existente
                    lblClienteEdit.Text = LocalizationProvider.Instance["MensajeClienteYaExisteEnLaBase"];
                    lblClienteEditLine2.Text = LocalizationProvider.Instance["MensajeCargueLosDatosComerciales"];
                    lnkAgregarClienteNuevoDesdeEdit.Visible = true;
                    CargarClienteExistente(searchResult.Resultados[0]);
                }
                else
                {
                    // Hay varios que coinciden, hay que elegir uno, muestro la lista
                    SeleccionarCliente(searchResult);
                }

                // Precargo la factura
                if (this.Modo == ModoPantalla.Venta)
                {
                    this.txtFactura_1.Value = this.txtSearchFactura.Text;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void CargarClienteNuevo(string dniOrEmail)
        {
            PtoVentaRegistroCliente cliente = new PtoVentaRegistroCliente();

            lblClienteEdit.Text = LocalizationProvider.Instance["MensajeClienteNoExisteEnBase"];
            lblClienteEditLine2.Text = LocalizationProvider.Instance["MensajeCargueDatosCliente"];
            lnkAgregarClienteNuevoDesdeEdit.Visible = false;

            //imgCustomerEdit.ImageUrl = "/Images/Plus.png";
            CargarClienteExistente(cliente);
            btnBitacora.Visible = false;
            btnVentas.Visible = false;

            if (dniOrEmail.Contains("@"))
            {
                this.txtEmail.Text = dniOrEmail;
            }
            else if (Regex.IsMatch(dniOrEmail, @"^\d+$"))
            {
                this.txtDNI.Text = dniOrEmail;
            }
            else
            {
                this.txtNombre.Text = dniOrEmail;
            }
        }

        protected void btnAgregarNuevoContacto_Click(object sender, EventArgs e)
        {
            try
            {
                string dniOrEmail = this.txtDniEmail.Text;
                CargarClienteNuevo(dniOrEmail);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                if (RememberMode)
                {
                    if (Modo == ModoPantalla.EdicionContacto)
                    {
                        EntrarEnModoActualizacion();
                    }
                    else if (Modo == ModoPantalla.Venta)
                    {
                        EntrarEnModoVenta();
                    }
                    else
                    {
                        EntrarEnModoSinEspecificar();
                    }
                }
                else
                {
                    EntrarEnModoSinEspecificar();
                }

                customerCurrent = null;
                RegistroClienteList = null;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                SaveCustomer();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnModoVenta_Click(object sender, EventArgs e)
        {
            try
            {
                RememberMode = this.chkRecordarMiDecision.Checked;
                EntrarEnModoVenta();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnModoActualizar_Click(object sender, EventArgs e)
        {
            try
            {
                RememberMode = this.chkRecordarMiDecision.Checked;
                EntrarEnModoActualizacion();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkIrAInicio_Click(object sender, EventArgs e)
        {
            try
            {
                EntrarEnModoSinEspecificar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}